package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.MyPagerAdapter;
import com.jdy.haoduoaiteacher.adapter.OnPainPointSelectListener;
import com.jdy.haoduoaiteacher.adapter.PainPointAdapter;
import com.jdy.haoduoaiteacher.adapter.PainPointCustomAdapter;
import com.jdy.haoduoaiteacher.enums.SelectionMode;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.PainPointItem;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LePreference;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.RippleView;
import com.jdy.haoduoaiteacher.view.RippleView.OnRippleCompleteListener;
import com.jdy.haoduoaiteacher.widget.CustomCommonDialog;
import com.jdy.haoduoaiteacher.widget.MyViewPager;
import com.jdy.haoduoaiteacher.widget.PopWinShare;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoaiteacher.R;

@SuppressLint({ "InflateParams", "HandlerLeak" })
public class MyPainPointSelectActivity extends BaseActivity implements
        OnClickListener, OnPageChangeListener {

  @InjectView(id = R.id.select_recom, click = true)
  private RelativeLayout select_recom;
  @InjectView(id = R.id.select_custom, click = true)
  private RelativeLayout select_custom;
//  @InjectView(id = R.id.tv_recomHabit)
//  private TextView tv_recomHabit;
  @InjectView(id = R.id.tv_customHabit)
  private TextView tv_customHabit;
//  @InjectView(id = R.id.beacon)
//  private ImageView beacon;
  @InjectView(id = R.id.vpager)
  private MyViewPager vpager;
  @InjectView(id = R.id.bottomlyt)
  private LinearLayout bottomlyts;
  @InjectView(id = R.id.delete, click = true)
  private Button delete;
  @InjectView(id = R.id.select, click = true)
  private Button select;
//  @InjectView(id = R.id.toplyt)
//  private LinearLayout toplyt;
//  @InjectView(id = R.id.bealyt)
//  private LinearLayout bealyt;
  @InjectView(id = R.id.commit_btn, click = true)
  private Button mCommitBtn;

  private View page1;
  private View page2;
  private LayoutInflater mInflater;
//  private int offset = 0;
  private int currIndex = 1;
  private List<View> views;
  private DisplayMetrics dm = null;
//  private int screenW;
//  private LayoutParams params;

  // page1
  private LinearLayout emptylayout1;
  private RippleView reloadRippleView1;
  private ListView listView1;
  private ImageView img_defaultfail1;
  private Button btnReload1;

  // page2
  private LinearLayout emptylayout2;
  private RippleView reloadRippleView2;
  private ListView listView2;
  private ImageView img_defaultfail2;
  private Button btnReload2;

  private PainPointAdapter mPainPointAdapter;
  private PainPointCustomAdapter mCustomPainPointAdapter;

  private ArrayList<PainPointItem> mStoryArrayList;
  private ArrayList<PainPointItem> mRadioArrayList;
  private LeUser mLeUser;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    setContentView(R.layout.mypainpointselect);

    mTitleText.setTextColor(0xff000000);
    setTitle("添加课程");

    mSelectedPainPointIds = new ArrayList<Integer>();
    mSelectedPainPointIds2 = new ArrayList<Integer>();

    initUpRightBtn();

    initialize();
    initHandler();
    initListener();
    InitViewPager();
   // loadRecomHabitData();
    loadCustomHabitData();
  }

  private void fillRecomHabitList(boolean loadFail) {
    if (mPainPointAdapter == null) {
      if (mStoryArrayList != null && !mStoryArrayList.isEmpty()) {
        mPainPointAdapter = new PainPointAdapter(this, mStoryArrayList);
      } else {
        mPainPointAdapter = new PainPointAdapter(this,
                new ArrayList<PainPointItem>());
      }

      listView1.setAdapter(mPainPointAdapter);
    } else {
      mPainPointAdapter.notifyDataSetChanged();
    }

    if (loadFail) {
      emptylayout1.setVisibility(View.VISIBLE);
      btnReload1.setVisibility(View.VISIBLE);
      img_defaultfail1.setBackgroundResource(R.drawable.defailt_fail);
    } else {
      if (mPainPointAdapter.getCount() == 0) {
        emptylayout1.setVisibility(View.VISIBLE);
        btnReload1.setVisibility(View.GONE);
        img_defaultfail1.setBackgroundResource(R.drawable.empty_mylove);
      } else {
        emptylayout1.setVisibility(View.GONE);
      }
    }

    mPainPointAdapter.setSelectedList(mSelectedPainPointIds);
    mPainPointAdapter
            .setPainPointSelectListener(new OnPainPointSelectListener() {
              @Override
              public void onPainPointSelect(int id, boolean selected) {
                if (selected) {
                  if (!mSelectedPainPointIds.contains(id)) {
                    mSelectedPainPointIds.add(id);
                  }

                  mCommitBtn.setText("提交好习惯培养计划 (已选 "
                          + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");
                } else {
                  if (mSelectedPainPointIds.contains(id)) {
                    int index = mSelectedPainPointIds.indexOf(id);
                    mSelectedPainPointIds.remove(index);
                    mCommitBtn.setText("提交好习惯培养计划 (已选 "
                            + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");
                  }
                }
              }
            });

  //  listView1.setAdapter(mPainPointAdapter);
    listView1.setItemsCanFocus(true);
    listView1.setFocusable(false);
    listView1.setFocusableInTouchMode(false);
    listView1.setClickable(false);

    mPainPointAdapter.notifyDataSetChanged();
  }

  /**
   * 自定义习惯
   * @param loadFail
   */
  private void fillCustomHabitList(boolean loadFail) {
    if (mCustomPainPointAdapter == null) {
      if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
        mCustomPainPointAdapter = new PainPointCustomAdapter(this, mRadioArrayList);
      } else {
        mCustomPainPointAdapter = new PainPointCustomAdapter(this,
                new ArrayList<PainPointItem>());
      }

      listView2.setAdapter(mCustomPainPointAdapter);
    } else {
        if (mRadioArrayList != null) {
            mCustomPainPointAdapter.setData(mRadioArrayList);
        }
      mCustomPainPointAdapter.notifyDataSetChanged();
    }

    if (loadFail) {
      emptylayout2.setVisibility(View.VISIBLE);
      btnReload2.setVisibility(View.VISIBLE);
      img_defaultfail2.setBackgroundResource(R.drawable.defailt_fail);
    } else {
      if (mCustomPainPointAdapter.getCount() == 0) {
        emptylayout2.setVisibility(View.VISIBLE);
        btnReload2.setVisibility(View.GONE);
        img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
      } else {
        emptylayout2.setVisibility(View.GONE);
      }
    }

    mCustomPainPointAdapter.setSelectedList(mSelectedPainPointIds2);
    mCustomPainPointAdapter
            .setPainPointSelectListener(new OnPainPointSelectListener() {
              @Override
              public void onPainPointSelect(int id, boolean selected) {
                if (selected) {
                  if (!mSelectedPainPointIds2.contains(id)) {
                    mSelectedPainPointIds2.add(id);
                  }

                  mCommitBtn.setText("提交好习惯培养计划 (已选 "
                          + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");
                } else {
                  if (mSelectedPainPointIds2.contains(id)) {

                    int index = mSelectedPainPointIds2.indexOf(id);

                    mSelectedPainPointIds2.remove(index);

                    mCommitBtn.setText("提交好习惯培养计划 (已选 "
                            + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size()) + "个)");
                  }
                }
              }
            });

    //  listView1.setAdapter(mPainPointAdapter);
    listView2.setItemsCanFocus(true);
    listView2.setFocusable(false);
    listView2.setFocusableInTouchMode(false);
    listView2.setClickable(false);
    mCustomPainPointAdapter.notifyDataSetChanged();
  }

  private ArrayList<Integer> mSelectedPainPointIds;
  private ArrayList<Integer> mSelectedPainPointIds2;

//  private void loadRecomHabitData() {
//    new CustomAsyncTask(this, new IAsyncTask() {
//      @Override
//      public void onRecieveData(Activity activity, ResponseResult result) {
//        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
//
//          mSelectedPainPointIds.clear();
//
//          if (mStoryArrayList != null) {
//            mStoryArrayList.clear();
//          }
//
//          ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
//                  .getInstance().deserialize(result.data, ArrayList.class,
//                          PainPointItem.class);
//
//          for (PainPointItem ppi : list) {
//            mStoryArrayList.add(ppi);
//            if (ppi.selected) {
//              mSelectedPainPointIds.add(ppi.id);
//            }
//          }
//
//          mCommitBtn.setText("提交好习惯培养计划 (已选 " + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size())
//                  + "个)");
//
//          fillRecomHabitList(false);
//        } else {
//          mStoryArrayList.clear();
//          fillRecomHabitList(true);
//        }
//
//        loadCustomHabitData();
//      }
//
//      @Override
//      public ResponseResult doInbackground(Activity activity) {
//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//
//        if (mGlobalLeUser != null) {
//          param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
//        } else {
//          LeUser lu = MyTeacherApp.getInstance().getUser();
//          if (lu == null) {
//            lu = Tools.restoreLeUser();
//          }
//          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
//        }
//
//        return HttpUtils.startRequest(HttpUtils.API_URL
//                        + HttpUtils.GET_PAINPOINT_LIST_GET, param_,
//                HttpUtils.TAG_GET_REQUEST);
//      }
//    }).execute();
//  }

  private void loadCustomHabitData() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {

          mSelectedPainPointIds2.clear();

          if (mRadioArrayList != null) {
            mRadioArrayList.clear();
          }

          ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
                  .getInstance().deserialize(result.data, ArrayList.class,
                          PainPointItem.class);

          for (PainPointItem ppi : list) {
            mRadioArrayList.add(ppi);
            if (ppi.enable ==1) {
              mSelectedPainPointIds2.add(ppi.id);
            }
          }

          mCommitBtn.setText("提交好习惯培养计划 (已选 " + (mSelectedPainPointIds.size() + mSelectedPainPointIds2.size())
                  + "个)");
          fillCustomHabitList(false);
        } else {
          mRadioArrayList.clear();
          fillCustomHabitList(true);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        if (mGlobalLeUser != null) {
          param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        } else {
          LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
          if (lu == null) {
            lu = Tools.restoreLeUser();
          }
          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        }

        return HttpUtils.startRequest(HttpUtils.API_URL
                        + HttpUtils.GET_CUSTOMPAINPOINT_LIST_GET/*HttpUtils.GET_PAINPOINT_LIST_GET*/, param_,
                HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void initialize() {
    mLeUser = MyTeacherApp.getInstance().getUserTeacher();

    mStoryArrayList = new ArrayList<>();
    mRadioArrayList = new ArrayList<>();

    dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm); // 得到 屏幕的宽度
//    screenW = dm.widthPixels;
//    params = beacon.getLayoutParams();
//    params.width = screenW / 6; // 设置 控件 cursor 图片的 宽度 是 屏宽的 2/5
//    beacon.setLayoutParams(params);
//
//    ViewHelper.setTranslationX(beacon, screenW / 6);

    views = new ArrayList<View>(); // 布局集合
    mInflater = LayoutInflater.from(this);

    page1 = mInflater.inflate(R.layout.recomhabitlayout, null);
    emptylayout1 = (LinearLayout) page1.findViewById(R.id.emptylayout);
    reloadRippleView1 = (RippleView) page1.findViewById(R.id.reloadRippleView);
    img_defaultfail1 = (ImageView) page1.findViewById(R.id.img_defaultfail);
    btnReload1 = (Button) page1.findViewById(R.id.reload);
    listView1 = (ListView) page1.findViewById(R.id.content_views);

    page2 = mInflater.inflate(R.layout.customhabitlayout, null);
    emptylayout2 = (LinearLayout) page2.findViewById(R.id.emptylayout);
    reloadRippleView2 = (RippleView) page2.findViewById(R.id.reloadRippleView);
    listView2 = (ListView) page2.findViewById(R.id.content_views);
    img_defaultfail2 = (ImageView) page2.findViewById(R.id.img_defaultfail);
    btnReload2 = (Button) page2.findViewById(R.id.reload);

    //views.add(page1);
    views.add(page2);

    //offset = screenW / 2;
  }

  private void InitViewPager() {
    vpager.setAdapter(new MyPagerAdapter(views));
    vpager.setCurrentItem(0);
  }

  private void initHandler() {
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
      }
    };
  }

  private void initListener() {
    vpager.setOnPageChangeListener(this);


    reloadRippleView1
            .setOnRippleCompleteListener(new OnRippleCompleteListener() {
              @Override
              public void onComplete(RippleView rippleView) {
              //  loadRecomHabitData();
              }
            });

    reloadRippleView2
            .setOnRippleCompleteListener(new OnRippleCompleteListener() {
              @Override
              public void onComplete(RippleView rippleView) {
                loadCustomHabitData();
              }
            });

    listView1.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                              long arg3) {
//        Intent intent = new Intent();
//        intent.setClass(MyPainPointSelectActivity.this, StoryDetailActivity.class);
//        intent.putExtra("id", mStoryArrayList.get(arg2).episode.album_id);
//        intent.putExtra("sort", mStoryArrayList.get(arg2).episode.sort); // 第几集，高亮
//        startActivity(intent);
      }
    });

    listView2.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                              long arg3) {
        Intent intent = new Intent();
        intent.setClass(MyPainPointSelectActivity.this, AddHabitClockActivity.class);

        intent.putExtra("isedit", true);
        intent.putExtra("custompainpoint", mRadioArrayList.get(arg2));

//        intent.putExtra("id", mRadioArrayList.get(arg2).episode.album_id);
//        intent.putExtra("sort", mRadioArrayList.get(arg2).episode.sort); // 第几集，高亮


         // startActivityForResult(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class), 100);
          startActivityForResult(intent,100);
      }
    });
  }

  PopWinShare popWinShare;

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_CANCELED) {
      return;
    }
    switch (requestCode) {
      case 100:
        loadCustomHabitData();
        break;
    }
  }

  class OnClickLintener implements OnClickListener{

    @Override
    public void onClick(View v) {
      switch (v.getId()) {
        case R.id.layout_addhabit:
      //    startActivity(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class));
          startActivityForResult(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class), 100);

          if (popWinShare!=null) {
            popWinShare.dismiss();
          }
          break;
        case R.id.layout_edithabit:
          popWinShare.dismiss();

          if (!bottomlyts.isShown()) {
          bottomlyts.setVisibility(View.VISIBLE);
                    img_upright.setImageResource(R.drawable.cancle);

            mCommitBtn.setVisibility(View.GONE);
          vpager.setScanScroll(false);
          if (currIndex == 1 && mCustomPainPointAdapter != null) {
            mCustomPainPointAdapter.setEditor(true);
            mCustomPainPointAdapter.notifyDataSetChanged();
          }

//          toplyt.setVisibility(View.GONE);
//          bealyt.setVisibility(View.GONE);
          mBackImageButton.setVisibility(View.INVISIBLE);
        } else {
            bottomlyts.setVisibility(View.GONE);
            mCommitBtn.setVisibility(View.VISIBLE);
            vpager.setScanScroll(true);
            img_upright.setImageResource(R.drawable.add_habit_icon);

          if (currIndex == 1 && mCustomPainPointAdapter != null) {
           mCustomPainPointAdapter.setEditor(false);

            if (mRadioArrayList != null) {
              for (PainPointItem item : mRadioArrayList) {
                item.isChecked = false;
              }
            }
           mCustomPainPointAdapter.notifyDataSetChanged();
          }

//          toplyt.setVisibility(View.VISIBLE);
//          bealyt.setVisibility(View.VISIBLE);
          getbtn_right().setBackgroundResource(R.drawable.edit_btn);
          mBackImageButton.setVisibility(View.VISIBLE);
        }

          break;

        default:
          break;
      }
    }
  }

  private void initUpRightBtn() {
    mBackImageButton.setImageResource(R.drawable.black_back);
    titleLayout.setBackgroundColor(0xffffffff);

    img_upright.setVisibility(View.VISIBLE);
    img_upright.setImageResource(R.drawable.add_habit_icon);
    img_upright.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (currIndex == 0) {
          //startActivity(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class));
          startActivityForResult(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class), 100);
          if (popWinShare!=null) {
            popWinShare.dismiss();
          }
        } else {

           if (bottomlyts.isShown()) {
               bottomlyts.setVisibility(View.GONE);
               mCommitBtn.setVisibility(View.VISIBLE);
               vpager.setScanScroll(true);
               img_upright.setImageResource(R.drawable.add_habit_icon);

               if (currIndex == 1 && mCustomPainPointAdapter != null) {
                   mCustomPainPointAdapter.setEditor(false);

                   if (mRadioArrayList != null) {
                       for (PainPointItem item : mRadioArrayList) {
                           item.isChecked = false;
                       }
                   }
                  // mCustomPainPointAdapter.setData(mRadioArrayList);

                 if (mCustomPainPointAdapter.getCount() == 0) {
                   emptylayout2.setVisibility(View.VISIBLE);
                   btnReload2.setVisibility(View.GONE);
                   img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
                 } else {
                   emptylayout2.setVisibility(View.GONE);
                 }

                   mCustomPainPointAdapter.notifyDataSetChanged();
               }

//               toplyt.setVisibility(View.VISIBLE);
//               bealyt.setVisibility(View.VISIBLE);
               getbtn_right().setBackgroundResource(R.drawable.edit_btn);
               mBackImageButton.setVisibility(View.VISIBLE);
           } else {
               if (popWinShare == null) {
                   OnClickLintener paramOnClickListener = new OnClickLintener();
                   popWinShare = new PopWinShare(MyPainPointSelectActivity.this, paramOnClickListener, Tools.getPixelByDip(MyPainPointSelectActivity.this,160), Tools.getPixelByDip(MyPainPointSelectActivity.this,160));
                   popWinShare.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                       @Override
                       public void onFocusChange(View v, boolean hasFocus) {
                           if (!hasFocus) {
                               popWinShare.dismiss();
                           }
                       }
                   });
               }

               popWinShare.setFocusable(true);
               popWinShare.showAsDropDown(img_upright, 0, 0);
               popWinShare.update();
           }



        }
      }
    });
  }

  private Dialog notificationTipDlg;
  long prelongTim = 0;
  private boolean hasFinish;

  private ArrayList<PainPointItem> mPainPointListSelect;

  public void showNotificationTipDialog() {
    LayoutInflater inflater = getLayoutInflater();
    final View layout = inflater.inflate(R.layout.painpoint_dlg, null);// 获取自定义布局

    TextView tv_babyage = (TextView) layout.findViewById(R.id.tv_babyage);
    if (tv_babyage != null
            && Tools.isNotEmpty(MyTeacherApp.getInstance().kidAge)) {
      tv_babyage.setText("您的宝贝的年龄是" + MyTeacherApp.getInstance().kidAge
              + ",");
    }

    notificationTipDlg = new Dialog(this, R.style.custom_dialog);
    notificationTipDlg.setContentView(layout);
    notificationTipDlg.setCancelable(false);
    notificationTipDlg.show();

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        if (hasFinish) {
          if (notificationTipDlg != null) {
            notificationTipDlg.dismiss();
            notificationTipDlg = null;
          }

          mPainPointListSelect = new ArrayList<PainPointItem>();
          for (PainPointItem ppi : mStoryArrayList) {
            if (mSelectedPainPointIds.contains(ppi.id)) {
              ppi.selected = true;
              mPainPointListSelect.add(ppi);
            }

            if (mSelectedPainPointIds2.contains(ppi.id)) {
              ppi.enable = 1;
              mPainPointListSelect.add(ppi);
            }
          }

          String jsonString = JsonSerializer.getInstance().serialize(
                  mPainPointListSelect);
          LePreference.getInstance().save("selectedpainpoint", jsonString);

          Intent intent = new Intent(MyPainPointSelectActivity.this,
                  MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);
          finish();
        }
      }
    }, 3000);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.commit_btn:

        showNotificationTipDialog();

        prelongTim = System.currentTimeMillis();

        hasFinish = false;

        new CustomAsyncTask(this, new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            hasFinish = true;
            long curTime = System.currentTimeMillis();

            if ((curTime - prelongTim) > 3200) {
              if (notificationTipDlg != null) {
                notificationTipDlg.dismiss();
                notificationTipDlg = null;
              }

              if (result.isSuccess()) {

                mPainPointListSelect = new ArrayList<PainPointItem>();
                for (PainPointItem ppi : mStoryArrayList) {
                  if (mSelectedPainPointIds.contains(ppi.id)) {
                    ppi.selected = true;
                    mPainPointListSelect.add(ppi);
                  }

                  if (mSelectedPainPointIds2.contains(ppi.id) ) {
                    ppi.enable = 1;
                    mPainPointListSelect.add(ppi);
                  }
                }

                String jsonString = JsonSerializer.getInstance().serialize(
                        mPainPointListSelect);
                LePreference.getInstance().save("selectedpainpoint", jsonString);

                Intent intent = new Intent(activity, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
              }
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            HashMap<String, Object> param_ = new HashMap<String, Object>();
            String ids = convertList2String(mSelectedPainPointIds);
            String ids2 = convertList2String(mSelectedPainPointIds2);
          //  Log.e(TAG, ids);

            if (mGlobalLeUser != null) {
              param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
            } else {
              LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
              if (lu == null) {
                lu = Tools.restoreLeUser();
              }
              param_.put(HttpUtils.TAG_SNO_I, lu.sno);
            }

            if (Tools.isNotEmpty(ids)) {
              param_.put("habit_ids", ids);
            }

            if (Tools.isNotEmpty(ids2)) {
              param_.put("habit_customized_ids", ids2);
            }
            return HttpUtils.startRequest(HttpUtils.API_URL
                            + HttpUtils.UPDATE_PAINPOINT_POST, param_,
                    HttpUtils.TAG_POST_REQUEST);
          }
        }).execute();

        break;

      case R.id.select_recom:
        vpager.setCurrentItem(0);
        break;
      case R.id.select_custom:
        vpager.setCurrentItem(1);
        break;
      case R.id.delete:

        if (currIndex == 0) {
          deleteStory();
        } else {
          deleteRadio();
        }
        break;
      case R.id.select:
        if (select.getText().toString().equals("全选")) {
         /* if (currIndex == 0 && mPainPointAdapter != null) {
           // mPainPointAdapter.setSelectMode(SelectionMode.SELECT_ALL);
            mPainPointAdapter.notifyDataSetChanged();
          } else */
         if (currIndex == 1 && mCustomPainPointAdapter != null) {
          //  mRadioAdapter.setSelectMode(SelectionMode.SELECT_ALL);
            mCustomPainPointAdapter.setSelectMode(SelectionMode.SELECT_ALL);
            mCustomPainPointAdapter.notifyDataSetChanged();
          }

          select.setText("取消全选");
        } else if (select.getText().toString().equals("取消全选")) {
          /*if (currIndex == 0 & mPainPointAdapter != null) {
           // mPainPointAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
            mPainPointAdapter.notifyDataSetChanged();
          } else */
          if (currIndex == 1 && mCustomPainPointAdapter != null) {
          //  mRadioAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
            mCustomPainPointAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
            mCustomPainPointAdapter.notifyDataSetChanged();
          }

          select.setText("全选");
        }
        break;
      default:
        break;
    }
  }

  private String convertList2String(ArrayList<Integer> ids) {
    String result = "";
    if (ids != null) {
      if (ids.size() == 0) {
        return "0";
      }
      int i = 0;
      int size = ids.size();
      for (; i < size; i++) {
        result += ids.get(i);
        if (i != size - 1) {
          result += ",";
        }
      }
    }
    return result;
  }

  private void deleteRadio() {
    int selectCount = 0;
    if (mRadioArrayList != null) {
      for (PainPointItem item : mRadioArrayList) {
        if (item != null && item.isChecked) {
          ++selectCount;
        }
      }
    }

    if (selectCount > 0) {
      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
              MyPainPointSelectActivity.this).setMessage("确定删除吗？").setTitle("删除提示")
              .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                }
              }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                  if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
                    final List<PainPointItem> selectedRecordings = new ArrayList<PainPointItem>();
                    String storyIds = "";

                    for (PainPointItem item : mRadioArrayList) {
                      if (item.isChecked) {
                        selectedRecordings.add(item);
                        storyIds += item.id;
                        storyIds += ",";
                      }
                    }

                    if (Tools.isNotEmpty(storyIds)) {
                      storyIds = storyIds.substring(0, storyIds.length() - 1);
                    }

                    if (selectedRecordings.size() > 0) {
                      showloading("");
                      final String finalStoryIds = storyIds;
                      new CustomAsyncTask(MyPainPointSelectActivity.this,
                              new IAsyncTask() {
                                @Override
                                public void onRecieveData(Activity activity,
                                                          ResponseResult result) {

                                  // if (result != null && result.isSuccess()) {
                                  for (PainPointItem rItem : selectedRecordings) {
                                    mCustomPainPointAdapter.remove(rItem);
                                  }
                                  mCustomPainPointAdapter.removeSelection();

                                  if (Tools.isNotNullStr(result.data)) {
                                    Toast.makeText(MyPainPointSelectActivity.this,
                                            result.data, Toast.LENGTH_SHORT).show();
                                  }
                                  // }

                                  dismissLoading();
                                }

                                @Override
                                public ResponseResult doInbackground(Activity activity) {
                                  if (mLeUser == null) {
                                    mLeUser = Tools.restoreLeUser();
                                  }

                                  HashMap<String, Object> param_ = new HashMap<String, Object>();
                                  param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                                 // param_.put("ids", finalStoryIds);
                                  return HttpUtils.startRequest(HttpUtils.HOST_API
                                                  + "/api/2.0/operation/habit/habits_customized/" + finalStoryIds,
                                          param_, HttpUtils.TAG_DELETE_REQUEST);
                                }
                              }).execute();

                    }
                    dialog.dismiss();
                  }
                }
              });
      cdb.create().show();
    } else {
      toastShow("未选中任何条目!");
    }
  }

  private void deleteStory() {
//    int selectCount = 0;
//    if (mStoryArrayList != null) {
//      for (LeFavoriteItem item : mStoryArrayList) {
//        if (item != null && item.isChecked) {
//          ++selectCount;
//        }
//      }
//    }
//
//    if (selectCount > 0) {
//      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
//              MyPainPointSelectActivity.this).setMessage("确定删除吗？").setTitle("删除提示")
//              .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                  dialog.dismiss();
//                }
//              }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int id) {
//
//                  if (mStoryArrayList != null && !mStoryArrayList.isEmpty()) {
//                    final List<LeFavoriteItem> selectedRecordings = new ArrayList<LeFavoriteItem>();
//                    String storyIds = "";
//
//                    for (LeFavoriteItem item : mStoryArrayList) {
//                      if (item.isChecked) {
//                        selectedRecordings.add(item);
//                        storyIds += item.id;
//                        storyIds += ";";
//                      }
//                    }
//
//                    if (Tools.isNotEmpty(storyIds)) {
//                      storyIds = storyIds.substring(0, storyIds.length() - 1);
//                    }
//
//                    if (selectedRecordings.size() > 0) {
//                      showloading("");
//                      final String finalStoryIds = storyIds;
//                      new CustomAsyncTask(MyPainPointSelectActivity.this,
//                              new IAsyncTask() {
//                                @Override
//                                public void onRecieveData(Activity activity,
//                                                          ResponseResult result) {
//
//                                  dismissLoading();
//                                  // if (result != null && result.isSuccess()) {
//                                  for (LeFavoriteItem rItem : selectedRecordings) {
//                                    mPainPointAdapter.remove(rItem);
//                                  }
//                                  mPainPointAdapter.removeSelection();
//
//                                  if (Tools.isNotNullStr(result.data)) {
//                                    Toast.makeText(MyPainPointSelectActivity.this,
//                                            result.data, Toast.LENGTH_SHORT).show();
//                                  }
//                                  // }
//                                }
//
//                                @Override
//                                public ResponseResult doInbackground(Activity activity) {
//                                  if (mLeUser == null) {
//                                    mLeUser = Tools.restoreLeUser();
//                                  }
//
//                                  HashMap<String, Object> param_ = new HashMap<String, Object>();
//                                  param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
//                                  param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//                                  return HttpUtils.startRequest(HttpUtils.HOST_API
//                                                  + "/api/2.0/member/favorite/" + finalStoryIds,
//                                          param_, HttpUtils.TAG_DELETE_REQUEST);
//                                }
//                              }).execute();
//
//                    }
//                    dialog.dismiss();
//                  }
//                }
//              });
//      cdb.create().show();
//    } else {
//      toastShow("未选中任何条目!");
//    }
  }

  @Override
  public void onPageScrollStateChanged(int arg0) {
  }

  @Override
  public void onPageScrolled(int arg0, float arg1, int arg2) {
  }

  @Override
  public void onPageSelected(int arg0) {
    Animation animation = null;
    switch (arg0) {
      case 0:
//        if (currIndex == 1) {
//          animation = new TranslateAnimation(offset, 0, 0, 0);
//        }

//        tv_recomHabit.setTextColor(0xff2bacfc);
//        tv_customHabit.setTextColor(0xff626262);

        break;
      case 1:
//        if (currIndex == 0) {
//          animation = new TranslateAnimation(0, offset, 0, 0);
//        }
//        tv_recomHabit.setTextColor(0xff626262);
//        tv_customHabit.setTextColor(0xff2bacfc);

        break;
    }
    currIndex = arg0;

//    if (animation != null) {
//      animation.setFillAfter(true);
//      animation.setDuration(200);
//      beacon.startAnimation(animation);
//    }
  }

}
